package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/jinzhu/gorm"
	"huodo/models"
	"io"
	"os"
	"strconv"
	"strings"
)

func (c *MainController) Add() {
	//跨域
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	HuoDoName := c.GetString("HuoDoName")
	price, _ := c.GetFloat("price")
	BaoMingTime := c.GetString("BaoMingTime")
	ChanJiaTime := c.GetString("ChanJiaTime")
	Address := c.GetString("Address")
	num, _ := c.GetInt("num")
	BaoNum, _ := c.GetInt("BaoNum")
	status := c.GetString("status")
	createName := c.GetString("createName")
	file, img, ferr := c.GetFile("img")
	if ferr != nil {
		c.Data["json"] = Res{500, "文件上传失败", nil}
		c.ServeJSON(true)
		return
	}
	if HuoDoName == "" || price == 0.00 || num == 0.00 || Address == "" || BaoNum == 0.00 {
		c.Data["json"] = Res{500, "数据不能为空", nil}
		c.ServeJSON(true)
		return
	}
	if BaoMingTime == "" || ChanJiaTime == "" || status == "" || num == 0.00 {
		c.Data["json"] = Res{500, "数据不能为空", nil}
		c.ServeJSON(true)
		return
	}
	fmt.Println("文件大小为", img.Size/1024, "kb")
	//判断文件大小
	if img.Size/1024 > 100 {
		c.Data["json"] = Res{500, "文件大小不能大于100kb", nil}
		c.ServeJSON(true)
		return
	}
	imglast := strings.LastIndex(img.Filename, ".")
	imgindex := img.Filename[imglast+1:]
	fmt.Println("文件类型为", imgindex)
	imgtype := "png"

	if strings.Contains(imgtype, imgindex) {
		fmt.Println("文件类型符合")
	} else {
		c.Data["json"] = Res{500, "文件类型不符合", nil}
		c.ServeJSON(true)
		return
	}

	//存储文件
	imgsta := "C:\\Users\\a\\Desktop\\8.12月考\\huodo\\static\\img/" + img.Filename
	fileimg, _ := os.Create(imgsta)
	io.Copy(fileimg, file)

	data := models.HouDo{
		Model:       gorm.Model{},
		HuoDoName:   HuoDoName,
		Price:       price,
		BaoMingTime: BaoMingTime,
		ChanJiaTime: ChanJiaTime,
		Address:     Address,
		Num:         num,
		BaoNum:      BaoNum,
		Status:      status,
		CreateName:  createName,
		Img:         imgsta,
	}
	models.DB.Create(&data)
	c.Data["json"] = Res{200, "新增成功", data}
	c.ServeJSON(true)

}
func (c *MainController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var data []models.HouDo
	models.DB.Find(&data)
	c.Data["json"] = Res{200, "列表查询成功", data}
	c.ServeJSON(true)

}
func (c *MainController) Show() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id")
	itoa := strconv.Itoa(id)
	var data models.HouDo
	getshow := models.RedisDB.Get("show" + itoa)
	if getshow.Val() != "" {
		fmt.Println("有数据")
		json.Unmarshal([]byte(getshow.Val()), &data)
	} else {
		fmt.Println("无数据")
		data = models.HouDo{
			Model: gorm.Model{ID: uint(id)},
		}
		models.DB.Debug().Find(&data)
		marshal, _ := json.Marshal(&data)
		models.RedisDB.Set("show"+itoa, marshal, 0)
	}

	c.Data["json"] = Res{200, "详情查询成功", data}
	c.ServeJSON(true)
}
